package com.jrh.web.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jrh.biz.brand.BrandService;
import com.jrh.biz.feature.FeatureService;
import com.jrh.biz.img.ImgUploadService;
import com.jrh.biz.product.ProductService;
import com.jrh.biz.product.set.ProductSetService;
import com.jrh.common.constant.JrhBizConstant;
import com.jrh.dal.CategoryDao;
import com.jrh.domain.entity.Brand;
import com.jrh.domain.entity.ImgAd;
import com.jrh.domain.entity.Product;
import com.jrh.web.admin.form.AdminFormCopier;
import com.jrh.web.admin.form.AdminProductForm;

@Controller
@RequestMapping("/sales/product")
public class AdminProductController {

    private static final int  smallImgOutputWidth  = 110;

    private static final int  smallImgOutputHeight = 110;

    @Autowired
    private ProductService    productService;
    @Autowired
    private CategoryDao       categoryDao;
    @Autowired
    private ProductSetService productSetService;
    @Autowired
    private BrandService      brandService;
    @Autowired
    private FeatureService    featureService;
    @Autowired
    private ImgUploadService  imgUploadService;

    @RequestMapping("list")
    public String index(Integer pageIndex, HttpServletRequest request, HttpServletResponse response, Model model) {
        Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
        if (brand == null) {
            return "/admin/error";
        }
        if (pageIndex == null) {
            pageIndex = 1;
        }
        model.addAttribute("pageData",
                           productService.getAllProductInBrand(brand.getId(), pageIndex, JrhBizConstant.SIZE_PER_PAGE));
        return "sales/product/list";
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/enable/{id}")
    public String enable(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
            if (brand == null) {
                return Boolean.FALSE.toString();
            }
            Product product = productService.getProductById(id);
            return String.valueOf(productService.updateProductStatus(product, true));
        } catch (Exception e) {
            return Boolean.FALSE.toString();
        }
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/disable/{id}")
    public String disable(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
            if (brand == null) {
                return Boolean.FALSE.toString();
            }
            Product product = productService.getProductById(id);
            return String.valueOf(productService.updateProductStatus(product, false));
        } catch (Exception e) {
            return Boolean.FALSE.toString();
        }
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/delete/{id}")
    public String delete(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
            if (brand == null) {
                return Boolean.FALSE.toString();
            }
            productService.deleteProduct(id);
            return String.valueOf(true);
        } catch (Exception e) {
            return Boolean.FALSE.toString();
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/create")
    public String create(HttpServletRequest request, HttpServletResponse response, Model model) {
        Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
        if (brand == null) {
            return "/admin/error";
        }
        model.addAttribute("brand", brand);
        model.addAttribute("categorys", categoryDao.listAllCategory());
        model.addAttribute("productSets", productSetService.listSetsByBrandId(3));
        return "sales/product/create";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public String doCreate(AdminProductForm productForm, HttpServletRequest request, HttpServletResponse response) {
        Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
        if (brand == null) {
            return "/admin/error";
        }
        productForm.setBrandId(brand.getId());

        Product product = AdminFormCopier.convert(productForm, new Product());
        assemblyProduct(product, productForm);

        productService.createProduct(product);
        return "redirect:/sales/product/list.htm";
    }

    private void assemblyProduct(Product product, AdminProductForm productForm) {
        if (productForm != null && productForm.getImageUrlFile() != null && productForm.getImageUrlFile().getSize() > 0) {
            String coverImgPath = imgUploadService.upload(productForm.getImageUrlFile(), "product_logo");
            product.setImgUrl(coverImgPath);
        } else {
            product.setImgUrl(productForm.getImageUrlFilePath());
        }
        List<ImgAd> adList = new ArrayList<ImgAd>();
        if (productForm != null && productForm.getShowImageUrlFile() != null
            && productForm.getShowImageUrlFile().length > 0) {

            for (MultipartFile file : productForm.getShowImageUrlFile()) {
                if (file == null || file.getSize() <= 0) {
                    continue;
                }
                String coverImgPath = imgUploadService.upload(file, "product_detail");
                String smallImgUrl = imgUploadService.resize(coverImgPath, smallImgOutputWidth, smallImgOutputHeight);
                ImgAd imgAd = new ImgAd();
                imgAd.setImgPath(coverImgPath);
                imgAd.setMinImgPath(smallImgUrl);
                adList.add(imgAd);
            }
        }
        if (productForm.getShowImageUrlFilePath() != null) {
            String[] filePath = productForm.getShowImageUrlFilePath();
            String[] minFilePath = productForm.getShowMinImageUrlFilePath();
            for (int i = 0; i < filePath.length; i++) {
                ImgAd imgAd = new ImgAd();
                imgAd.setImgPath(filePath[i]);
                imgAd.setMinImgPath(minFilePath[i]);
                adList.add(imgAd);
            }
        }
        product.setImgAds(adList);
        if(product.getFavourite()==null){
            product.setFavourite(0L);
        }
        if(product.getComments()==null){
            product.setComments(0L);
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/update/{id}")
    public String edit(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response, Model model) {
        Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
        if (brand == null) {
            return "/admin/error";
        }
        Product product = productService.getProductById(id);
        if (product == null) {
            return "/admin/error";
        }
        model.addAttribute("brand", brand);
        model.addAttribute("categorys", categoryDao.listAllCategory());
        model.addAttribute("productSets", productSetService.listSetsByBrandId(3));
        model.addAttribute("product", product);
        return "sales/product/update";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/update")
    public String doEdit(AdminProductForm productForm, HttpServletRequest request, HttpServletResponse response) {
        Brand brand = BrandSalesManager.getBrandByUser(brandService, request, response);
        if (brand == null) {
            return "/admin/error";
        }
        productForm.setBrandId(brand.getId());

        Product product = AdminFormCopier.convert(productForm, new Product());
        assemblyProduct(product, productForm);

        productService.updateProductBySale(product);
        return "redirect:/sales/product/list";
    }

}
